/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import Entity.User;


/**
 *
 * @author Edwin
 */
public class UserDAO {
    
    public static User persistAdmin(User entity, EntityManager em) {
        em.persist(entity);
		return em.find(User.class, entity.getId());
    }
    
    
    public User correctLoginAdmin(User entity, EntityManager em){
        String jpql = "SELECT u FROM User u";
        Query query = em.createQuery(jpql);
        List<User> resultados = query.getResultList();
        for(int i=0;i<resultados.size();i++){
            /**
             * aqui se compara lo que me envia 
             * la vista con los datos 
             * que me trae la BD
            */
            if ((resultados.get(i).getLogin().compareTo(entity.getLogin())==0)&&
                    (resultados.get(i).getPassword().compareTo(entity.getPassword())==0)){
                return resultados.get(i);
            }
        }
        return null;
    }
    
    
    
    public User correctRegisterUser(User entity, EntityManager em){
        User entityUser = entity;
        String jpql = "SELECT u FROM User u";
        Query query = em.createQuery(jpql);
        List<User> results = query.getResultList();
        int cont=0;
        for(int i=0;i<results.size();i++){
            /**
             * aqui se compara lo que me envia 
             * la vista con los datos que me trae la BD
            */
            cont=cont+1;
            if ((results.get(i).getLogin().compareTo(entityUser.getLogin())==0)){
                return null;
            }
        }
        if(cont==results.size())
            return null;
        /**
         * insertar entity en la BD
         */
        return entityUser;
    }
    
    
    
     public List<User> getUserList(EntityManager em){
 
        String jpql = "SELECT u FROM User u";
        Query query = em.createQuery(jpql);
        List<User> results = query.getResultList();
        
        return results;
	}
}
